﻿using System.Threading;
using System.Threading.Tasks;
using Linker.TaskCenter.Helpers;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Threading;

namespace Linker.TaskCenter.Tasks
{
    public class TaskWorker : IRunnable, ISingletonDependency
    {
        private readonly ILogger<TaskWorker> _logger;
        private readonly CSRedisHelper _redisHelper;


        private readonly ITaskManager _taskManager;

        public TaskWorker(
            ILogger<TaskWorker> logger,
            CSRedisHelper redisHelper,
            ITaskManager taskManager)
        {
            _redisHelper = redisHelper;
            _logger = logger;
            _taskManager = taskManager;
        }

        public Task StartAsync(CancellationToken cancellationToken = new())
        {
            _logger.LogInformation("Start Execute TaskWorker...");
            return Task.Factory.StartNew(() => { ExecuteService(); }, TaskCreationOptions.LongRunning);
        }

        public Task StopAsync(CancellationToken cancellationToken = new())
        {
            _logger.LogInformation("Stop Execute TaskWorker!");
            return Task.CompletedTask;
        }


        private async Task ExecuteService()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    var data = _redisHelper.BRPop<RequestMessageData>(AppConsts.TaskQueueKey);
                    if (data != null)
                    {
                        _taskManager.ExecuteTaskAsync(data);
                    }
                }
            });
        }
    }
}